import React, { forwardRef, useEffect, useState } from 'react';
import Modals from '@/components/modals/Modals';
import { Form, Select, Switch, Row, Col, Radio, message } from 'antd';
import { Input, Segmented, RequiredLabel } from '@/components/eai-design';
import TagInput from '@/components/inputs/TagInput';
import Tip from '@/components/tip/Tip';
import './ParamsEditModal.scss';

interface Props {
  modelData?: any;
  onCancel: () => void;
  onSubmit: (values: any) => void;
  okText?: string;
  title?: string;
  onClose?: () => void;
  open?: boolean;
  [key: string]: any;
}

const ParamsEditModal = forwardRef<any, Props>(
  (
    {
      modelData,
      onCancel,
      onSubmit,
      okText,
      title,
      onClose,
      ...props
    },
    ref,
  ) => {
    const [verticalLoading, setVerticalLoading] = useState(false);
    const [form] = Form.useForm();

    const type = Form.useWatch('type', form);
    const configType = Form.useWatch('configType', form);
    const constraint = Form.useWatch('constraint', form);

    const createIntegerInput = (placeholder?: string) => (
      <Input
        type='number'
        step="1"
        min="0"
        placeholder={placeholder || "整数，如：5"}
        onBlur={(e) => {
          const value = e.target.value;
          if (value && !Number.isInteger(Number(value))) {
            message.warning('请输入整数');
            e.target.value = Math.round(Number(value)).toString();
          }
        }}
        onKeyDown={(e) => {
          if (e.key === '.') {
            e.preventDefault();
          }
        }}
      />
    );

    const createFloatInput = (placeholder?: string) => (
      <Input
        type='number'
        step="any"
        placeholder={placeholder || "支持小数，如：5.5"}
      />
    );

    const segmentedOptions = [
      { label: '无', value: '无' },
      { label: '枚举', value: '枚举' },
      { label: '约束', value: '约束' },
    ];

    useEffect(() => {
      console.log(modelData, '--modelData');

      form.setFieldsValue({
        name: modelData?.name,
        description: modelData?.description,
        required: modelData?.required || false,
        type: modelData?.type,
        in: modelData?.in,
        constraint: modelData?.constraint || '无',
        enum: modelData?.enum || [],
        configType: modelData?.configType,
        pattern: modelData?.pattern,
        format: modelData?.format,
        minimum: modelData?.minimum,
        maximum: modelData?.maximum,
        multipleOf: modelData?.multipleOf,
        minItems: modelData?.minItems,
        maxItems: modelData?.maxItems,
        minLength: modelData?.minLength,
        maxLength: modelData?.maxLength,
      });
    }, [modelData, props.open, form]);

    const handleApiVerify = (values: any) => {
      const numberFields = ['minLength', 'maxLength', 'minItems', 'maxItems', 'minimum', 'maximum', 'multipleOf'];
      numberFields.forEach(field => {
        if (values[field]) {
          values[field] = Number(values[field]);
        }
      });
      onSubmit({
        ...values,
        index: modelData?.index !== undefined ? modelData?.index : null
      });
    };

    const init = () => {
      setVerticalLoading(false);
      onCancel();
    };

    const renderConstraintFields = () => {
      if (constraint !== '约束') return null;

      return (
        <>
          {type === undefined && null}
          {type?.includes('string') && (
            <>
              <Form.Item
                name="configType"
                style={{ width: '100%' }}
                rules={[{ required: true, message: '请选择' }]}
              >
                <Radio.Group>
                  <Radio value="pattern">pattern</Radio>
                  <Radio value="format">format</Radio>
                </Radio.Group>
              </Form.Item>

              {configType === 'pattern' && (
                <Form.Item
                  label={<RequiredLabel>pattern</RequiredLabel>}
                  rules={[{ required: true, message: '请输入正则表达式' }]}
                  name="pattern"
                  required={false}
                >
                  <Input placeholder='请输入正则表达式' />
                </Form.Item>
              )}

              {configType === 'format' && type?.includes('string') && (
                <Form.Item
                  label={<RequiredLabel>format</RequiredLabel>}
                  rules={[{ required: true, message: '请选择format' }]}
                  name="format"
                  required={false}
                >
                  <Select
                    placeholder="请选择"
                    style={{ width: '100%' }}
                  >
                    <Select.Option value="date-time">date-time</Select.Option>
                    <Select.Option value="time">time</Select.Option>
                    <Select.Option value="date">date</Select.Option>
                    <Select.Option value="duration">duration</Select.Option>
                    <Select.Option value="email">email</Select.Option>
                    <Select.Option value="hostname">hostname</Select.Option>
                    <Select.Option value="ipv4">ipv4</Select.Option>
                    <Select.Option value="ipv6">ipv6</Select.Option>
                    <Select.Option value="uuid">uuid</Select.Option>
                  </Select>
                </Form.Item>
              )}
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    label="字符串最小值"
                    name="minLength"
                  >
                    {createIntegerInput()}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="字符串最大值"
                    name="maxLength"
                  >
                    {createIntegerInput()}
                  </Form.Item>
                </Col>
              </Row>
            </>
          )}
          {(type?.includes('number') || type?.includes('integer')) && (
            <>
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    label={<div className='flex items-center'>
                      <div>Minimum</div>
                      <Tip className='ml-1 text-[#B7BDC7]' title='该数字必须大于或等于该值' />
                    </div>}
                    name="minimum">
                    {createFloatInput()}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={<div className='flex items-center'>
                      <div>Maximum</div>
                      <Tip className='ml-1 text-[#B7BDC7]' title='该数字必须小于或等于该值' />
                    </div>}
                    name="maximum">
                    {createFloatInput()}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={<div className='flex items-center'>
                      <div>MultipleOf</div>
                      <Tip className='ml-1 text-[#B7BDC7]' title='该数字必须是该值的倍数' />
                    </div>}
                    name="multipleOf">
                    {createFloatInput()}
                  </Form.Item>
                </Col>
              </Row>
            </>
          )}
        </>
      );
    };

    return (
      <Modals
        title="添加参数"
        onOk={form.submit}
        onCancel={init}
        {...props}
        width={720}
        confirmLoading={verticalLoading}
        okText="确认"
        onClose={onClose}
        modelContentClassName="!mr-0 !pr-0"
      >
        <Form layout="vertical" className="form !mr-6" form={form} onFinish={handleApiVerify}>
          <Form.Item
            label={<RequiredLabel>参数名</RequiredLabel>}
            rules={[{ required: true, message: '请输入参数名' }]}
            name="name"
            required={false}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label={<RequiredLabel>参数说明</RequiredLabel>}
            rules={[{ required: true, message: '请输入参数说明' }]}
            name="description"
            required={false}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label={<RequiredLabel>必须返回</RequiredLabel>}
            rules={[{ required: true, message: '请选择' }]}
            name="required"
            required={false}
          >
            <Switch />
          </Form.Item>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={<RequiredLabel>数据类型</RequiredLabel>}
                rules={[{ required: true, message: '请选择' }]}
                name="type"
                required={false}
              >
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  <Select.Option value="string">string</Select.Option>
                  <Select.Option value="integer">integer</Select.Option>
                  <Select.Option value="boolean">boolean</Select.Option>
                  <Select.Option value="number">number</Select.Option>
                  <Select.Option value="array<number>">array&lt;number&gt;</Select.Option>
                  <Select.Option value="array<integer>">array&lt;integer&gt;</Select.Option>
                  <Select.Option value="array<string>">array&lt;string&gt;</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={<RequiredLabel>传入方式</RequiredLabel>}
                name="in"
                rules={[{ required: true, message: '请选择传入方式' }]}
                required={false}
              >
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Select.Option value="body">body</Select.Option>
                  <Select.Option value="path">path</Select.Option>
                  <Select.Option value="query">query</Select.Option>
                  <Select.Option value="header">header</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          {type != 'boolean' && (
            <>
              <div className="flex items-center mb-4">
                <div className="w-1/2 text-sm flex-shrink-0">
                  数据要求
                  <span className="text-error text-sm mr-1">*</span>
                </div>
                <div className="w-1/2 pl-3">
                  <Form.Item
                    name="constraint"
                    style={{ width: '100%' }}
                    rules={[{ required: true, message: '请选择' }]}
                    noStyle
                  >
                    <Segmented
                      options={segmentedOptions}
                      className="params-segmented"
                    />
                  </Form.Item>
                </div>
              </div>

              {constraint === '枚举' && (
                <Form.Item
                  label={<RequiredLabel>枚举值</RequiredLabel>}
                  rules={[{ required: true, message: '请输入枚举值' }]}
                  name="enum"
                  validateTrigger={['onSubmit']}
                  required={false}
                >
                  <TagInput
                    className=""
                    defaultTags={modelData?.enum}
                    placeholder="输入示例值，并按回车"
                    minRows={1}
                    warningMessage="示例值已存在"
                    tagType={type?.includes('number') || type?.includes('integer') ? 'number' : 'string'}
                    onChange={(tags) => {
                      const values = form.getFieldsValue();
                      console.log(values);
                    }}
                  />
                </Form.Item>
              )}

              {constraint === '约束' && renderConstraintFields()}
            </>
          )}
          {(type === 'array' || type?.includes('array')) && (
            <>
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    label={<div className='flex items-center'>
                      <div>MinItems</div>
                      <Tip className='ml-1 text-[#B7BDC7]' title='数组至少包含这么多项' />
                    </div>}
                    name="minItems">
                    {createIntegerInput()}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={<div className='flex items-center'>
                      <div>MaxItems</div>
                      <Tip className='ml-1 text-[#B7BDC7]' title='数组至多包含这么多项' />
                    </div>}
                    name="maxItems">
                    {createIntegerInput()}
                  </Form.Item>
                </Col>
              </Row>
            </>
          )}
        </Form>
      </Modals>
    );
  },
);

ParamsEditModal.displayName = 'ParamsEditModal';

export default ParamsEditModal;
